<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Agent;

class AgentController extends Controller{
    public function logout(Request $req){
        Agent::where('id',$req->agent->id)->update(array('token'=>''));
        return response()->json(array('code'=>1))->cookie('superbar_agenttoken',false,-1);
    }
    
    public function login(Request $req){
        $mobile = $req->post('mobile');
        $passwd = $req->post('passwd');
        if (empty($mobile)) wxresp(0,'请输入号码');
        if (empty($passwd)) wxresp(0,'请输入密码');
        $agent = Agent::where('mobile',$mobile)->first();
        if (empty($agent)) wxresp(0,'账号或密码不正确');
        if ($agent->passwd != md5($passwd)) wxresp(0,'账号或密码不正确');
        $agent->token = md5(time());
        $agent->save();
        return response()->json(array('code'=>1))->cookie('superbar_agenttoken',base64_encode($agent->token),365*24*3600);
    }
    
    public function reg(Request $req,$code = ''){
        if ($req->method() == 'POST') {
            $mobile = $req->post('mobile');
            $passwd = $req->post('passwd');
            if (empty($mobile)) wxresp(0,'请输入号码');
            if (empty($passwd)) wxresp(0,'请输入密码');
            $agent = Agent::where('mobile',$mobile)->first();
            if (!empty($agent)) wxresp(0,'该手机号已注册');
            $agent = new Agent();
            $agent->paid = $req->agent->id;
            $agent->mobile = $mobile;
            $agent->passwd = md5($passwd);
            $agent->code = Agent::getUnicode();
            $agent->ip = getip();
            $agent->lasttime = $agent->createtime = time();
            $agent->token = md5(time());
            $agent->save();
            return response()->json(array('code'=>1))->cookie('superbar_agenttoken',base64_encode($agent->token),365*24*3600);
        }
        return redirect("https://".$req->host()."/{$code}#/pages/index/reg");
    }
}